#!/usr/bin/env bash

#基准目录
base_dir=~

#站点名称
site_name=ctc-docker

#ctc-docker目录
ctc_docker_dir=${base_dir}/${site_name}

#ctc-docker备份文件
ctc_docker_tar=${base_dir}/${site_name}.tar.gz

#成功信息输出
success_print() {
  echo -e "\033[32m $1 \033[0m"
}

#失败信息输出
error_print() {
  echo -e "\033[31m $1 \033[0m"
}

#系统判断
os_type() {
  os=$(grep "^ID=" /etc/os-release)
  if [[ ${os} =~ 'centos' ]]; then
    echo 'centos'
  elif [[ ${os} =~ 'ubuntu' ]]; then
    echo 'ubuntu'
  elif [[ ${os} =~ 'debian' ]]; then
    echo 'debian'
  else
    echo 'other'
  fi
}

#判断是否root用户
if [[ $EUID -ne 0 ]]; then
    error_print "\n------ error: this script must be run as root ------\n" 1>&2
    exit 1
fi

#安装git和curl
if [ "$(os_type)" = 'ubuntu' ] || [ "$(os_type)" = 'debian' ]; then
  sudo apt-get update && apt-get install -y curl git
elif [ "$(os_type)" = 'centos' ]; then
  sudo yum update && yum install -y curl git
else
  error_print "\n------ we only support (ubuntu|debian|centos) currently ------\n"
  exit 1
fi

if [ ! -e ${ctc_docker_tar} ]; then
  error_print "\n------ error: ctc-docker.tar.gz not found ------\n"
  exit 1
fi

#解压ctc-docker.tar.gz
cd ${base_dir} && tar -xzf ${site_name}.tar.gz

#安装docker
if [ -z "$(command -v docker)" ]; then
  sudo bash ${base_dir}/get_docker.sh
  sudo systemctl enable docker
  sudo systemctl start docker
fi

if [ -z "$(command -v docker)" ]; then
  error_print "\n------ error: docker command not found, please try again ------\n"
  exit 1
fi

if [ ! -d '/etc/docker' ]; then
  sudo mkdir -p '/etc/docker'
fi

#docker镜像加速
if [ ! -e '/etc/docker/daemon.json' ]; then
  sudo echo '{"registry-mirrors": ["https://mirror.ccs.tencentyun.com"]}' | tee /etc/docker/daemon.json
  sudo systemctl daemon-reload
  sudo systemctl restart docker
  sudo chmod 666 /var/run/docker.sock
fi

docker_compose_url="https://download.koogua.com/docker-compose-$(uname -s)-$(uname -m)"

#安装docker-composer（路径转小写）
if [ -z "$(command -v docker-compose)" ]; then
  sudo curl -L "${docker_compose_url,,}" -o /usr/local/bin/docker-compose
  sudo chmod +x /usr/local/bin/docker-compose
fi

if [ -z "$(command -v docker-compose)" ]; then
  error_print "\n------ error: docker-compose command not found, please try again ------\n"
  exit 1
fi

#切换到基准目录
cd ${ctc_docker_dir} || exit

#启动容器
docker-compose up -d

docker_ps=$(docker ps)

if [[ "${docker_ps}" =~ 'nginx' ]]; then
  success_print "nginx service ok\n"
else
  error_print "nginx service failed\n"
fi

if [[ "${docker_ps}" =~ 'php' ]]; then
  success_print "php service ok\n"
else
  error_print "php service failed\n"
fi

if [[ "${docker_ps}" =~ 'mysql' ]]; then
  success_print "mysql service ok\n"
else
  error_print "mysql service failed\n"
fi

if [[ "${docker_ps}" =~ 'redis' ]]; then
  success_print "redis service ok\n"
else
  error_print "redis service failed\n"
fi

if [[ "${docker_ps}" =~ 'xunsearch' ]]; then
  success_print "xunsearch service ok\n"
else
  error_print "xunsearch service failed\n"
fi
